// pages/service/sellCar.js
var $api = require('../../utils/api');
var util = require('../../utils/util');
var area_standard = require('../../utils/areaStandard');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    images: [], //图片上传数组
    frameNumber: "", //车架号
    city: "", //车辆位置所在城市
    carAge: "", //车龄
    brand: "", //品牌
    brandId:"",//品牌id
    name: "", //汽车名称
    phone: "", //联系方式
    vehicleType: "", //车辆类型
    registrationTime: "", //上牌时间
    price: "", //价格
    showMileage: "", //表显里程
    gearbox: "", //变速箱
    color: "", //颜色
    country: "", //国别
    carDisplacement: "", //排量
    inspectionDueTime: "", //年检到期
    compulsoryInsuranceDueTime: "", //强险到期
    content: "", //车辆描述
    checked: true,
    vehicle_type: '', //车辆类型
    autosize: {
      maxHeight: 50,
      minHeight: 50
    }, //输入框高度
    vehicleTypeColumns: [{
      text: "轿车",
      value: "car"
    }, {
      text: "越野车/SUV",
      value: "SUV"
    }, {
      text: "商务车/MPV",
      value: "MPV"
    }, {
      text: "跑车",
      value: "Sports_car"
    }, {
      text: "皮卡",
      value: "Pickup"
    }, {
      text: "面包车",
      value: "van"
    }, {
      text: "客车",
      value: "Passenger_car"
    }, {
      text: "货车",
      value: "truck"
    }, {
      text: "7座",
      value: "7_seats"
    }, {
      text: "房车",
      value: "Touring_car"
    }, {
      text: "敞篷车",
      value: "open_car"
    }, {
      text: "轿跑",
      value: "Coupe"
    }, {
      text: "新能源",
      value: "new_energy"
    }], //车型选择器属性值
    dateFormatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      } else if (type === 'day') {
        return `${value}日`;
      }
      return value;
    }, //时间返回格式
    minDate: new Date(1970, 0, 1).getTime(), //最小日期范围
    maxDate: new Date().getTime(), //最大日期范围
    nowDate: new Date().getTime(), //当前时间
    gearboxColumns: [{
      text: "手动",
      value: "manual"
    }, {
      text: "自动",
      value: "automatic"
    }, {
      text: "手自一体",
      value: "Hand_in_one"
    }, {
      text: "双离开",
      value: "Dual_clutch"
    }, {
      text: "CVT无极变",
      value: "CVT_continuously_variable"
    }, {
      text: "七档双离合速",
      value: "Seven_speed_dual_clutch"
    }], //变速箱选择器
    colorColumns: [{
      text: "黑色",
      value: "black"
    }, {
      text: "白色",
      value: "white"
    }, {
      text: "红色",
      value: "red"
    }, {
      text: "蓝色",
      value: "blue"
    }, {
      text: "灰色",
      value: "grey"
    }, {
      text: "绿色",
      value: "green"
    }, {
      text: "黄色",
      value: "yellow"
    }, {
      text: "银色",
      value: "silver"
    }, {
      text: "橙色",
      value: "orange"
    }, {
      text: "金色",
      value: "golden"
    }, {
      text: "紫色",
      value: "purple"
    }, {
      text: "香槟金色",
      value: "Champagne_gold"
    }, {
      text: "棕色",
      value: "brown"
    }, {
      text: "其他",
      value: "other"
    }], //颜色选择器
    countryColumns: [{
      text: "国系",
      value: "china"
    }, {
      text: "德系",
      value: "german"
    }, {
      text: "欧系",
      value: "european"
    }, {
      text: "日系",
      value: "japanese"
    }, {
      text: "法系",
      value: "france"
    }, {
      text: "美系",
      value: "america"
    }, {
      text: "韩系",
      value: "korean"
    }] //国别选择器
  },

  uploadImage: function(path) {
    return new Promise(function (resolve, reject) {
      $api.upLoad(path).then(res => {
        let resData = JSON.parse(res);
        if (resData.code == 1) {
          resolve(resData.data.url) ;
        }
      })
     })
  },
  //文件上传
  afterRead: function (event) {
    const files = event.detail.file;
    for (var index in files) {
      this.uploadImage(files[index].path).then(res => {
        let images = this.data.images;
        images.push({url : res})
        this.setData({
          images
        })
      }).catch(err => {  //请求失败
        console.log(err);
      });
    };

  },
  //图片上传前
  beforeRead(event) {
    const {
      file,
      callback
    } = event.detail;
    callback(file.type === 'image');
  },
  //删除上传
  delete: function (event) {
    let imgDelIndex = event.detail.index;
    let images = this.data.images;
    images.splice(imgDelIndex, 1);
    this.setData({
      images
    })
  },
  //发表、上架车源
  postCar: function (e) {
    let params;
    $api.postCar(params).then(res => {

    })
  },
  //打开位置选择器
  openCityPopup: function (e) {
    this.setData({
      cityColumns: area_standard.default,
      showCityPopup: true
    })
  },
  onCloseCityPopup: function (e) {
    this.setData({
      showCityPopup: false
    })
  },
  onChangeCityPopup: function (e) {
    let list = e.detail.values;
    //拼接后端接受的区域格式
    let region = list[0].name + "/" + list[1].name + "/" + list[2].name;
    this.setData({
      city: region,
      showCityPopup: false
    })
  },

  //打开品牌选择器
  openBrandSelection: function (e) {
    wx.navigateTo({
      url: '../index/brandSelection',
    })
  },

  //打开车型选择器
  showVehicleTypePopup: function (e) {
    this.setData({
      showVehicleTypePopup: true
    })
  },
  //关闭车型选择器
  onCloseVehicleTypePopup: function (e) {
    this.setData({
      showVehicleTypePopup: false
    })
  },
  onChangeVehicleType: function (e) {
    this.setData({
      vehicleType: e.detail.value,
      showVehicleTypePopup: false
    })
  },

  //打开上牌时间选择器
  showRegistrationTimePopup: function (e) {
    this.setData({
      showRegistrationTimePopup: true
    })
  },
  //关闭上牌时间选择器
  onCloseRegistrationTimePopup: function (e) {
    this.setData({
      showRegistrationTimePopup: false
    })
  },
  onChangeRegistrationTime: function (e) {
    let format = ['年', '月', '日']
    this.setData({
      registrationTime: util.formatTime2(e.detail, format),
      showRegistrationTimePopup: false
    })
  },
  // 打开变速箱选择器
  showGearboxPopup: function (e) {
    this.setData({
      showGearboxPopup: true
    })
  },
  onCloseGearboxPopup: function () {
    this.setData({
      showGearboxPopup: false
    })
  },
  onChangeGearbox: function (e) {
    this.setData({
      gearbox: e.detail.value,
      showGearboxPopup: false
    })
  },
  //打开颜色选择器
  showColorPopup: function (e) {
    this.setData({
      showColorPopup: true
    })
  },
  onCloseColorPopup: function (e) {
    this.setData({
      showColorPopup: false
    })
  },
  onChangeColor: function (e) {
    this.setData({
      color: e.detail.value,
      showColorPopup: false
    })
  },
  // 打开国别选择器
  showCountryPopup: function (e) {
    this.setData({
      showCountryPopup: true
    })
  },
  onCloseCountryPopup: function (e) {
    this.setData({
      showCountryPopup: false
    })
  },
  onChangeCountryPopup: function (e) {
    this.setData({
      country: e.detail.value,
      showCountryPopup: false
    })
  },
  //年检到期选择器
  showInspectionDueTimePopup: function (e) {
    this.setData({
      showInspectionDueTimePopup: true
    })
  },
  onCloseInspectionDueTimePopup: function (e) {
    this.setData({
      showInspectionDueTimePopup: false
    })
  },
  onChangeInspectionDueTime: function (e) {
    let format = ['年', '月', '日']
    this.setData({
      inspectionDueTime: util.formatTime2(e.detail, format),
      showInspectionDueTimePopup: false,
    })
  },
  //强险到期选择器
  showCompulsoryInsuranceDueTimePopup: function (e) {
    this.setData({
      showCompulsoryInsuranceDueTimePopup: true
    })
  },
  onCloseCompulsoryInsuranceDueTimePopup: function (e) {
    this.setData({
      showCompulsoryInsuranceDueTimePopup: false
    })
  },
  onChangeCompulsoryInsuranceDueTime: function (e) {
    let format = ['年', '月', '日']
    this.setData({
      compulsoryInsuranceDueTime: util.formatTime2(e.detail, format),
      showCompulsoryInsuranceDueTimePopup: false
    })
  },
  //发布车源
  release: function () {
    if (this.data.images != "" && this.data.city != "" && this.data.carAge != "" &&
      this.data.frame_number != "" && this.data.brand != "" && this.data.name != "" &&
      this.data.vehicleType.value != "" && this.data.registrationTime != "" && this.data.price != "" &&
      this.data.showMileage != "" && this.data.gearbox.value != "" && this.data.color.value != "" &&
      this.data.country.value != "" && this.data.carDisplacement != "" && this.data.inspectionDueTime != "" &&
      this.data.compulsoryInsuranceDueTime != "" && this.data.content != "") {
      let img_arr = '';
      for (let i = 0; i < this.data.images.length; i++) {
        img_arr += this.data.images[i].url + ','
      }
      let firstImage = this.data.images[0]['url'];
      //去除最后一个逗号
      let reg = /,$/gi;
      img_arr = img_arr.replace(reg, "");

      let params = {
        status: 0,
        images: img_arr,
        image: firstImage,
        city: this.data.city,
        car_age: this.data.carAge,
        phone: wx.getStorageSync('user_phone'),
        frame_number: this.data.frameNumber,
        brand_id: this.data.brandId,
        name: this.data.name,
        vehicle_type: this.data.vehicleType.value,
        Registration_time: util.timeToTimeStamp(this.data.registrationTime),
        price: this.data.price,
        show_mileage: this.data.showMileage,
        gearbox: this.data.gearbox.value,
        color: this.data.color.value,
        country: this.data.country.value,
        car_displacement: this.data.carDisplacement,
        Inspection_due_time: util.timeToTimeStamp(this.data.inspectionDueTime),
        Compulsory_insurance_due_time: util.timeToTimeStamp(this.data.compulsoryInsuranceDueTime),
        content: this.data.content
      }
      if (this.data.id) {
        params = {...params, ...{id: this.data.id}};
      }
      $api.postCar(params).then(res => {
        if (res.code == 1) {
          wx.navigateBack({
            delta: 1,
            success: function () {
              wx.showToast({
                title: '提交成功!',
                icon: 'none',
                duration: 2000 //持续的时间
              })
            }
          })
        }
      })
    } else {
      console.log
      wx.showToast({
        title: '请填写完整信息后提交!',
        icon: 'none',
        duration: 2000 //持续的时间
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  onLoad: function (option) {
    console.log(option);
    if (option.data) {
      var data = JSON.parse(option.data);
      // city: this.data.city,
      //   car_age: this.data.carAge,
      //   phone: wx.getStorageSync('user_phone'),
      //   frame_number: this.data.frameNumber,
      //   brand_id: this.data.brandId,
      //   name: this.data.name,
      //   vehicle_type: this.data.vehicleType.value,
      //   Registration_time: util.timeToTimeStamp(this.data.registrationTime),
      //   price: this.data.price,
      //   show_mileage: this.data.showMileage,
      //   gearbox: this.data.gearbox.value,
      //   color: this.data.color.value,
      //   country: this.data.country.value,
      //   car_displacement: this.data.carDisplacement,
      //   Inspection_due_time: util.timeToTimeStamp(this.data.inspectionDueTime),
      //   Compulsory_insurance_due_time: util.timeToTimeStamp(this.data.compulsoryInsuranceDueTime),
      //   content: this.data.content


      var list = data.images.split(',');
      var imagesArr = Object.keys(list).map(val => ({
        url: list[val]
    }))
    console.log(imagesArr);
      this.setData({
        'id': data.id,
        'images': imagesArr,
        'city': data.city,
        'carAge': data.car_age,
        'phone': data.phone,
        'frameNumber': data.frame_number,
        'brandId': data.brand_id,
        'brand': data.brand_name,
        'name': data.name,
        'vehicleType': {value :data.vehicle_type, text: data.vehicle_type_text},
        // 'vehicleType': data.vehicle_type_text,
        'registrationTime': util.formatTime2(data.Registration_time * 1000, ['年','月','日']),
        'price': data.price,
        'showMileage': data.show_mileage,
        'gearbox': {value: data.gearbox, text: data.gearbox_text},
        'color': {value: data.color, text: data.color_text},
        'country': {value: data.country, text: data.country_text},
        'carDisplacement': data.car_displacement,
        'inspectionDueTime': util.formatTime2(data.Inspection_due_time * 1000, ['年','月','日']),
        'compulsoryInsuranceDueTime': util.formatTime2(data.Compulsory_insurance_due_time * 1000, ['年','月','日']),
        'content': data.content,
        
      })
    }
    console.log(data);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})